package cn.shengchao.dubbo.api.wecom;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.shengchao.base.utils.SecureUtils;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainDomainService;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainExistLoader;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.base.TransResult;
import cn.shengchao.examstar.rpc.distribute.cs.UserCs;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.wecom.api.CpUserServiceInviteApi;
import cn.shengchao.examstar.rpc.wecom.dto.CpUserInviteSaveDto;
import cn.shengchao.examstar.rpc.wecom.dto.CpUserServiceInviteDto;
import cn.shengchao.examstar.rpc.wecom.req.CpUserInviteJmsYgChangeRto;
import cn.shengchao.examstar.rpc.wecom.req.CpUserInvitePageQuery;
import cn.shengchao.examstar.rpc.wecom.resp.CpUserCustomerVo;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import cn.shengchao.qywx.infrastrure.po.QywxUser;
import cn.shengchao.qywx.infrastrure.po.QywxUserServiceInvite;
import cn.shengchao.qywx.infrastrure.po.QywxUserSysbind;
import cn.shengchao.qywx.infrastrure.service.QywxUserService;
import cn.shengchao.qywx.infrastrure.service.QywxUserServiceInviteService;
import cn.shengchao.qywx.infrastrure.service.QywxUserSysbindService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.dreamlu.mica.core.utils.DesensitizationUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.core.exception.BaseException;

import java.util.*;

/**
 * @program: examstarapi
 * @description: 企微成员用户邀请关系
 * @author: Xiong weiqiang
 * @create: 2025-05-01 10:52
 */
@DubboService
public class CpUserServiceInviteDubboApi implements CpUserServiceInviteApi {
    @Autowired
    private QywxUserServiceInviteService  qywxUserServiceInviteService;
    @Autowired
    private DistributeNodeInfoService distributeNodeInfoService;
    @Autowired
    private DistributeNodeRoleChainDomainService distributeNodeRoleChainDomainService;
    @Autowired
    private DistributeNodeRoleChainExistLoader distributeNodeRoleChainExistLoader;
    @Autowired
    private QywxUserService qywxUserService;
    @Autowired
    private QywxUserSysbindService qywxUserSysbindService;
    @Autowired
    private UserRepository userRepository;
    @Override
    public void createUserServiceInviteRecord(CpUserServiceInviteDto cpUserServiceInviteDto) {
        long count = qywxUserServiceInviteService.count(
                Wrappers.lambdaQuery(QywxUserServiceInvite.class)
                        .eq(QywxUserServiceInvite::getUserId,cpUserServiceInviteDto.getUserId())
                        .eq(QywxUserServiceInvite::getDataStatus,0)
        );
        if (count > 0){
            qywxUserServiceInviteService.update(Wrappers.lambdaUpdate(QywxUserServiceInvite.class)
                    .eq(QywxUserServiceInvite::getUserId,cpUserServiceInviteDto.getUserId())
                    .set(QywxUserServiceInvite::getDataStatus,1)
                    .eq(QywxUserServiceInvite::getDataStatus,0)
            );
        }
        QywxUserServiceInvite qywxUserServiceInvite = new QywxUserServiceInvite();
        BeanUtil.copyProperties(cpUserServiceInviteDto,qywxUserServiceInvite);
        //获取服务人员微信id
        List<QywxUserSysbind> qywxUserSysbindList=qywxUserSysbindService.list(Wrappers.lambdaQuery(QywxUserSysbind.class)
                .eq(QywxUserSysbind::getSysUserId,cpUserServiceInviteDto.getServiceUserId())
        );
        if (CollUtil.isNotEmpty(qywxUserSysbindList)){
            List<String> idList=qywxUserSysbindList.stream().map(QywxUserSysbind::getQywxUserId).toList();
            List<QywxUser> qywxUserList=qywxUserService.list(Wrappers.lambdaQuery(QywxUser.class)
                    .in(QywxUser::getUserId,idList)
                    .eq(QywxUser::getStatus,"1")
                    .eq(QywxUser::getQrCodeStatus,1)
                    .isNotNull(QywxUser::getQrCodeUrl)
            );
            if (CollUtil.isNotEmpty(qywxUserList)){
                qywxUserServiceInvite.setServiceCpUserId(qywxUserList.getFirst().getUserId());
            }
        }
        qywxUserServiceInviteService.save(qywxUserServiceInvite);

    }

    @Override
    public PageResult<CpUserCustomerVo> queryCpUserInvitePage(CpUserInvitePageQuery pageQuery) {
        List<Long> chainUserIds=new ArrayList<>();
        if (pageQuery.getDistributeUserId()!=null){
            chainUserIds.add(pageQuery.getDistributeUserId());
            DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getOne(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                    .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                    .eq(DistributeNodeInfo::getUserId, pageQuery.getDistributeUserId())
                    .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            if (distributeNodeInfo!=null&&pageQuery.getDistributeUserId()!=null&&pageQuery.getIncludeLowLevel()!=null&&pageQuery.getIncludeLowLevel()==1){
                Map<Long, Set<Long>> lowNodeUserIdMap=distributeNodeRoleChainDomainService.getLowNodeUserIds(DistributeTypeEnum.TYPE_SALE.getType(), List.of(pageQuery.getDistributeUserId()), distributeNodeInfo.getDistributeRoleCode());
                lowNodeUserIdMap.values().forEach(chainUserIds::addAll);
            }
            pageQuery.setDistributeChainUserIds(chainUserIds);
        }
        PageResult<CpUserCustomerVo> pageResult=qywxUserServiceInviteService.queryCpUserInvitePage(pageQuery);

        if (CollUtil.isNotEmpty(pageResult.getList())){
            List<Long> distributeUserIds=pageResult.getList().stream().map(CpUserCustomerVo::getDistributeUserId).toList();
            List<User> userList=userRepository.getUserList(distributeUserIds);
            List<DistributeNodeInfo> distributeNodeInfos=distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                    .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                    .in(DistributeNodeInfo::getUserId, distributeUserIds)
                    .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            Map<Long,User> userMap=userList.stream().collect(HashMap::new,(k, v)->k.put(v.getId(),v),HashMap::putAll);
            Map<Long,DistributeNodeInfo> distributeNodeInfoMap=distributeNodeInfos.stream().collect(HashMap::new,(k,v)->k.put(v.getUserId(),v),HashMap::putAll);
            pageResult.getList().forEach(item->{
                String phone= SecureUtils.decryptFieldByAes(item.getStudentPhone());
                item.setStudentPhone(DesensitizationUtil.mobileNo(phone));
                if (item.getDistributeUserId()==0){
                    item.setDistributeUserPhone("平台");
                    item.setDistributeUserName("平台");
                }else {
                    User user=userMap.get(item.getDistributeUserId());
                    DistributeNodeInfo distributeNodeInfo1=distributeNodeInfoMap.get(item.getDistributeUserId());
                    item.setDistributeUserPhone(user==null?"": DesensitizationUtil.mobileNo(user.getPhone()));
                    item.setDistributeUserName(distributeNodeInfo1==null?"平台":distributeNodeInfo1.getFullName());
                }
            });
        }
        return pageResult;
    }

    @Override
    public TransResult<String> updateUserInviteRecord(CpUserInviteSaveDto saveRto) {
        //主要要记录分销商。
        Long distributeUserId=0L;
        String distributeCode="";
        if (!Objects.equals(saveRto.getInviteUserId(), UserCs.PLATFORM_USER_ID)){
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserId(saveRto.getInviteUserId(), DistributeTypeEnum.TYPE_SALE.getType());
            if (!existModel.isExist()){
                return TransResult.fail("保存用户邀请关系时发生错误：分销用户不存在");
            }
            DistributeNodeInfo distributeNodeInfo=existModel.getDistributeNodeInfo();
            if (distributeNodeInfo!=null){
                distributeCode=distributeNodeInfo.getDistributeRoleCode();
                if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
                    distributeUserId=distributeNodeInfo.getAdminUserId();
                }else if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode())){
                    //上级是加盟商
                    if (existModel.getUpLevelNodeInfo()!=null|| DistributeSaleRoleEnum.ROLE_DSPD.getCode().equals(existModel.getUpLevelNodeInfo().getDistributeRoleCode())){
                        distributeUserId=existModel.getUpLevelNodeInfo().getUserId();
                    }else {
                        distributeUserId=distributeNodeInfo.getUserId();
                    }
                }else if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD.getCode())){
                    distributeUserId=distributeNodeInfo.getUserId();
                }else {
                    throw new BaseException("保存用户邀请关系时发生错误：分销用户节点不合适");
                }
            }else {
                distributeCode=DistributeSaleRoleEnum.ROLE_YSXG.getCode();
                distributeUserId=UserCs.PLATFORM_USER_ID;
            }
        }else {
            distributeCode=DistributeSaleRoleEnum.ROLE_YSXG.getCode();
            distributeUserId=UserCs.PLATFORM_USER_ID;
        }

        QywxUserServiceInvite qywxUserServiceInvite=new QywxUserServiceInvite();
        qywxUserServiceInvite.setUserId(saveRto.getUserId());
        qywxUserServiceInvite.setServiceUserId(saveRto.getInviteUserId());
        qywxUserServiceInvite.setServiceCpUserId(saveRto.getInviteWxCpUserId());
        qywxUserServiceInvite.setServiceDistributeUserId(distributeUserId);
        qywxUserServiceInvite.setServiceDistributeCode(distributeCode);
        qywxUserServiceInviteService.update(Wrappers.lambdaUpdate(QywxUserServiceInvite.class)
                .eq(QywxUserServiceInvite::getUserId,saveRto.getUserId())
                .eq(QywxUserServiceInvite::getDataStatus,0)
                .set(QywxUserServiceInvite::getDataStatus,1)
        );
        qywxUserServiceInviteService.save(qywxUserServiceInvite);
        return TransResult.success("保存用户邀请关系成功");
    }
    @Transactional
    @Override
    public TransResult<String> batchUpdateUserInviteRecordForJmsYg(CpUserInviteJmsYgChangeRto jmsYgRto) {
        DistributeNodeInfo distributeNodeInfo1=distributeNodeInfoService.getOne(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                .eq(DistributeNodeInfo::getUserId, jmsYgRto.getUserId())
                .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
        DistributeNodeInfo distributeNodeInfo2=distributeNodeInfoService.getOne(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                .eq(DistributeNodeInfo::getUserId, jmsYgRto.getReplaceUserId())
                .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
        if (distributeNodeInfo1==null||distributeNodeInfo2==null){
            return TransResult.fail(distributeNodeInfo1==null?"被替代员工分销关系不存在":"替代用户分销关系不存在");
        }
        if (!distributeNodeInfo1.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
            return TransResult.fail("批量更改员工的学员企微邀请关系时发生错误："+"被替换用户非员工");
        }
        if (!distributeNodeInfo2.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
            return TransResult.fail("批量更改员工的学员企微邀请关系时发生错误："+"替代员工非员工");
        }
        List<QywxUserServiceInvite> qywxUserServiceInviteList=qywxUserServiceInviteService.list(Wrappers.lambdaQuery(QywxUserServiceInvite.class)
                .eq(QywxUserServiceInvite::getServiceUserId,jmsYgRto.getUserId())
                .eq(QywxUserServiceInvite::getDataStatus,0));
        List<Long> userIdList=qywxUserServiceInviteList.stream().map(QywxUserServiceInvite::getUserId).toList();
        if (CollUtil.isNotEmpty(qywxUserServiceInviteList)){
            qywxUserServiceInviteService.update(Wrappers.lambdaUpdate(QywxUserServiceInvite.class)
                    .eq(QywxUserServiceInvite::getServiceUserId,jmsYgRto.getUserId())
                    .set(QywxUserServiceInvite::getDataStatus,1)
                    .eq(QywxUserServiceInvite::getDataStatus,0)
            );
            List<QywxUserServiceInvite> qywxUserServiceInviteList1=new ArrayList<>();
            for (Long uid : userIdList){
                QywxUserServiceInvite qywxUserServiceInvite1=new QywxUserServiceInvite();
                qywxUserServiceInvite1.setUserId(uid);
                qywxUserServiceInvite1.setServiceUserId(jmsYgRto.getReplaceUserId());
                qywxUserServiceInvite1.setServiceCpUserId(jmsYgRto.getServiceCpUserId());
                qywxUserServiceInvite1.setServiceDistributeUserId(distributeNodeInfo2.getAdminUserId());
                qywxUserServiceInvite1.setServiceDistributeCode(distributeNodeInfo2.getDistributeRoleCode());
                qywxUserServiceInvite1.setDataStatus(0);
                qywxUserServiceInviteList1.add(qywxUserServiceInvite1);
            }
            qywxUserServiceInviteService.saveOrUpdateBatch(qywxUserServiceInviteList1);
        }


        return TransResult.success("批量更改员工的学员企微邀请关系成功");
    }
}